<template>
  <div class="login-card">
    <h1 style="color: gray">Login</h1>
    <el-form ref="ruleForm" status-icon class="demo-ruleForm">
      <el-form-item>
        <el-input
          type="text"
          v-model="form.username"
          :prefix-icon="User"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          type="password"
          v-model="form.password"
          :prefix-icon="Lock"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" round :loading="loading"
          >登 录</el-button
        >
        <el-button @click="resetForm" round>清 空</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style>
.login-card {
  width: 350px;
  margin: 0 auto;
  margin-top: 100px;
}

.demo-ruleForm {
  margin: 0 auto;
}
</style>
<script setup>
import { ref, reactive } from "vue"
import { ElMessage } from "element-plus"
import { useRouter, useRoute } from "vue-router"
const route = useRoute()
const router = useRouter()

const PASSWORD_REG =
  /^(?![0-9]+$)(?![a-z]+$)(?![A-Z]+$)(?!([^(0-9a-zA-Z)]|[\(\)])+$)([^(0-9a-zA-Z)]|[\(\)]|[a-z]|[A-Z]|[0-9]){6,16}$/

import qs from "qs"
import { User, Lock } from "@element-plus/icons-vue"

const BASE_URL = import.meta.env.VITE_API_BASE_URL

const form = reactive({
  username: "",
  password: "",
})

const loading = ref(false)

const submitForm = () => {
  console.log(form)
  if (form.username !== "" && form.password !== "") {
    if (PASSWORD_REG.test(form.password)) {
      loading.value = true
      fetch(`${BASE_URL}/user/login`, {
        method: "POST",
        mode: "cors",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: qs.stringify(form),
      })
        .then((response) => {
          return response.json()
        })
        .then((res) => {
          loading.value = false
          if (res.code == 0) {
            localStorage.setItem("token", res.data.token)
            localStorage.setItem("username", res.data.name)
            localStorage.setItem("usertype", res.data.usertype)
            ElMessage({
              message: "登录成功",
              type: "success",
            })
            setTimeout(() => {
              router.replace({
                path: "/list",
              })
            }, 1200)
          }
        })
    } else {
      ElMessage({
        message: "密码为6-16位，包含字母数字及特殊符号两种",
        type: "warning",
      })
    }
  } else {
    ElMessage({
      message: "账户和密码不能为空",
      type: "warning",
    })
  }
}

const resetForm = () => {
  form.username = ""
  form.password = ""
}
</script>
